<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button>添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column type="expand" label="详情">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', 'vcenter', index1 === 0 ? 'bdtop' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRight(scope.row, item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="['vcenter', index2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable @close="removeRight(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      type="warning"
                      closable
                      @close="removeRight(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                @click="showEditDialog(scope.row.id)"
                type="primary"
                size="mini"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                @click="removeUser(scope.row.id)"
                type="danger"
                size="mini"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-star-off"
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      @close="setRightDialogClose"
      title="添加用户"
      :visible.sync="rightDialogVisible"
      width="50%"
    >
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      roleList: [],
      // 控制对话框
      rightDialogVisible: false,
      // 权限数据
      rightList: [],
      // 树形控件
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中节点
      defaultKey: [],
      // 即将分配权限的id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await this.$http.get('roles')
      if (res.data.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data.data
    },
    // 删除角色
    async removeRight(role, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将删除该角色, 是否继续?',
        '警告',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      ).catch(err => err)
      if (confirmRes === 'confirm') {
        const res = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )
        if (res.data.meta.status !== 200) {
          return this.$message.error('删除失败！')
        }
        this.$message.success('删除成功')
        role.children = res.data.data
      }
    },
    // 对话款关闭事件
    setRightDialogClose() {
      this.defaultKey = []
    },
    // 分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id

      const res = await this.$http.get('rights/tree')
      if (res.data.meta.status !== 200) {
        return this.$message.error('权限数据获取失败')
      }
      this.rightList = res.data.data

      // 递归获取三级节点id
      this.getLeafKeys(role, this.defaultKey)
      this.rightDialogVisible = true
    },
    // 递归获取角色的所有三级权限id
    getLeafKeys(node, array) {
      // 当前节点不包含children即为三级节点
      if (!node.children) {
        return array.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, array)
      })
    },
    // 为角色分配权限
    async allotRights() {
      // 获取所有全选中和半选中项
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      // 以逗号拼接id
      const idStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })

      if (res.data.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('操作成功')
      this.getRoleList()
      this.rightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
